package net.lovesrc.allin.jobs.backup;

import com.alibaba.fastjson.JSONObject;
import com.zhouzhou.fastjava.http.Requests;
import net.lovesrc.allin.biz.cpct.CPCTService;
import net.lovesrc.allin.jobs.base.WorkTimeJob;
import org.apache.commons.lang3.RandomUtils;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Profile("live")
public class CpctMonitorTransferJob extends WorkTimeJob {

    @Autowired
    private CPCTService cpctService;

    @Override
    public void doRunOnce() {
        if (RandomUtils.nextInt(0, 6) == 3) {
            safeRun(() -> cpctService.resetNewOnePayPass());
        }

        Outer:
        for (; ; ) {
            JSONObject earlyRow = queryForRow(jdbcTemplate, "select * from t_cpct_transfer where status = 'Transfer_Success' order by lastCheckTime asc limit 1");
            if (earlyRow == null) {
                break;
            }
            String fromMobile = earlyRow.getString("fromMobile");
            String toMobile = earlyRow.getString("toMobile");
            JSONObject row = queryForRow(jdbcTemplate, "select * from t_cpct_sub_account where mobile = ?", fromMobile);
            jdbcTemplate.update("update t_cpct_transfer set lastCheckTime = ? where fromMobile = ?", new Date(), fromMobile);
            String cookies = row.getString("cookies");
            CookieStore cookieStore = Requests.toCookieStore(cookies);
            HttpClient httpClient = cpctService.ensureLogin(cookieStore, row);
            List<JSONObject> transferOrders = cpctService.getTransferOrders(httpClient);
            for (JSONObject transferOrder : transferOrders) {
                if (transferOrder.getIntValue("status") != 1) {
                    int effectRows = jdbcTemplate.update("update t_cpct_transfer set status = 'Transfer_Complete', successTime = ? where orderNum = ? and status = 'Transfer_Success'", new Date(), transferOrder.getString("transactionNum"));
                    if (effectRows > 0) {
                        cpctService.clearTransferPublicAddress(httpClient);
                        if (toMobile.length() == 11) {
                            notificationService.syncEmail("CPCT 交易成功");
                        } else {
                            notificationService.syncEmail("CPCT 交易成功, To: " + toMobile);
                        }
                        continue Outer;
                    }
                }
            }
            break;
        }
        cpctService.transferEth();
    }

    @Override
    protected long intervalMilliseconds() {
        return TimeUnit.SECONDS.toMillis(RandomUtils.nextInt(70, 140));
    }

}
